package com.ruoyan.controller;

import com.ruoyan.pojo.User;
import com.ruoyan.service.UserService;
import lombok.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Package: com.ruoyan.controller
 * @ClassName: UserController
 * @Author: ruoyan1998
 * @CreateTime: 2021/5/9 13:31
 * @Description:
 */
@Controller
@RequestMapping("/user")
public class UserController
{
    @Resource
    private UserService userService;

    @RequestMapping("/toSignIn")
    public String toSignIn()
    {
        return "toSignIn";
    }

    @RequestMapping("/SignIn")
    public String SignIn(User user, HttpServletRequest request, Model model)
    {
        int signin = userService.signin(user);

        if(signin <= 0)
        {
            request.setAttribute("msg","注册失败");
            model.addAttribute("msg","注册失败");
            return "toSignIn";
        }

        model.addAttribute("user",user);

        return "toLogin";
    }

    @RequestMapping("/toLogin")
    public String toLogin()
    {
        return "toLogin";
    }

    @RequestMapping({"/Login"})
    public String Login(String userName, String password, HttpServletRequest request,Model model)
    {
        User user = userService.login(userName, password);

        if(user == null)
        {
            model.addAttribute("msg","登录失败");
            return "toLogin";
        }

        model.addAttribute("user",user);

        request.getSession().setAttribute("user",user);

        return "allbook";
    }

    @RequestMapping({"/logout"})
    public String logout(HttpServletRequest request)
    {
        request.getSession().removeAttribute("user");

        return "toLogin";
    }
}
